import json


def format_channel_name(name):
    if name.startswith('CCTV'):
        return name.split('-')[0]
    if name == "东南卫视":
        return "福建东南卫视"
    return name


def fill_pd_json():
    pd_json_path = 'pd.json'
    with open(pd_json_path, 'r', encoding='utf - 8') as f:
        pd_json = json.load(f)

        # 启动时询问一次是否删除url
    choice = input("是否要删除频道的URL（y/n）: ")
    if choice.lower() == 'y':
        for channel in pd_json:
            keys_to_delete = [k for k in channel.keys() if k.startswith('url')]
            for key in keys_to_delete:
                del channel[key]
        print("已删除所有频道的URL。")

    m3u_count = 1
    while True:
        # 检查pd.json 哪些频道的url是空的
        empty_url_channels = []
        for channel in pd_json:
            url_keys = [k for k in channel.keys() if k.startswith('url')]
            all_url_empty = True
            for url_key in url_keys:
                if channel[url_key]:
                    all_url_empty = False
                    break
            if all_url_empty:
                empty_url_channels.append(channel["name"])
        print(f"在处理第{m3u_count}个.m3u文件之前，pd.json 中url为空的频道: {empty_url_channels}")

        m3u_file_path = input(f"请输入第{m3u_count}个.m3u文件的路径（如果没有更多文件请输入'q'退出）: ")
        if m3u_file_path == 'q':
            break

        m3u_url_dict = {}
        with open(m3u_file_path, 'r', encoding='utf - 8') as f:
            lines = f.readlines()
            i = 0
            while i < len(lines):
                if lines[i].startswith('#EXTINF'):
                    name = format_channel_name(lines[i].split(',')[1].strip())
                    url = lines[i + 1].strip()
                    if name not in m3u_url_dict:
                        m3u_url_dict[name] = [url]
                    else:
                        m3u_url_dict[name].append(url)
                    i += 1
                i += 1
            print(m3u_url_dict)

        no_url_channels = []
        replaced_channels = []
        for channel in pd_json:
            if "name" in channel:
                formatted_name = format_channel_name(channel["name"])
                if formatted_name in m3u_url_dict:
                    url_list = m3u_url_dict[formatted_name]
                    if "url" not in channel and url_list:
                        channel["url"] = url_list.pop(0)
                        replaced_channels.append(channel["name"])
                    elif "url1" not in channel and url_list:
                        channel["url1"] = url_list.pop(0)
                        replaced_channels.append(channel["name"])
                    elif "url2" not in channel and url_list:
                        channel["url2"] = url_list.pop(0)
                        replaced_channels.append(channel["name"])
                    elif "url3" not in channel and url_list:
                        channel["url3"] = url_list.pop(0)
                        replaced_channels.append(channel["name"])
                    elif "url4" not in channel and url_list:
                        channel["url4"] = url_list.pop(0)
                        replaced_channels.append(channel["name"])
                    elif "url5" not in channel and url_list:
                        channel["url5"] = url_list.pop(0)
                        replaced_channels.append(channel["name"])
                else:
                    no_url_channels.append(channel["name"])

        with open(pd_json_path, 'w', encoding='utf - 8') as f:
            json.dump(pd_json, f, indent=4, ensure_ascii=False)
        print(f"在处理{m3u_file_path}时，已替换的频道: {replaced_channels}")
        print(f"在处理{m3u_file_path}时，没有传入url的频道: {no_url_channels}")
        m3u_count += 1


fill_pd_json()

